package gen.tools.deploy;

import gen.tools.Widgets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.as.cli.CommandContext;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;

public class ReDepMemphis extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ReDepMemphis() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		
		final Widgets wid = new Widgets();
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		final boolean isDep = Boolean.parseBoolean( request.getParameter("isDep") );
		final long depId = Long.parseLong( request.getParameter("depId") );
		final String empId = request.getParameter("empId");
		final String squadId = request.getParameter("squadId");
		final String fileName = request.getParameter("fileName");
		final String apURL = request.getParameter("apURL");
        final String apUSR = request.getParameter("apUSR");
        final char[] apPWD = request.getParameter("apPWD").toCharArray();
        final String svnURL = request.getParameter("svnURL");
		final String svnUSR = request.getParameter("svnUSR");
        final int apPORT = Integer.parseInt( request.getParameter("apPORT") );
        String commandLine = "undeploy " + fileName + " --server-groups="+squadId+" --keep-content";
        Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
        String res = "";
        
		CommandContext cmdCtx = null;
		ModelControllerClient client = null;
		ModelNode requestNode = null;
		ModelNode result = null;
		
		boolean isMasterDataOK = false;	//若發生錯誤時，要留下錯誤訊息，以此判斷是要從單頭開始寫，還是單身
		
		try {
			if ( isDep ) {
				commandLine = "deploy --name=" + fileName + " --server-groups="+ squadId;
			}
			//取得部署記錄的ID
			int depMemphisSN = wid.getDepSN(depId);
			
			conn= wid.getConn();
			//表示目前還未創建，開始創建
			if ( !isDep ) {
				String strSQL = "INSERT INTO depmemphis (svnUSR,svnURL,depMemphisId,cDT,creatorId,depType) VALUES (?,?,?,?,?,?)";
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, svnUSR);
				ps.setString(2, svnURL);
				ps.setLong(3, depId);
				ps.setTimestamp(4, wid.cDT());
				ps.setString(5, empId);
				ps.setInt(6, 2); //表示為重新部署
				ps.execute();
				depMemphisSN = wid.getDepSN(depId);
			}
			isMasterDataOK = true;
			
			cmdCtx = wid.initCommandContext(apURL,apPORT,apUSR,apPWD);
			client = cmdCtx.getModelControllerClient();
			if (cmdCtx.getExitCode() == 0 && !cmdCtx.isTerminated()) {
				requestNode = cmdCtx.buildRequest(commandLine);
				result = client.execute(requestNode);
				res = result.get("outcome").toString().substring(1, result.get("outcome").toString().length()-1);
			}
			
			String isSuccess = "success".equalsIgnoreCase(res)?"t":"f";
			String strSQL = "INSERT INTO depmemphisdetail (depMemphisSN,depMemphisDetailId,squadId,fileName,fileVer,relativePath,isSuccess,errMsg,isAssume,isDep) VALUES (?,?,?,?,?,?,?,?,?,?)";
			ps = conn.prepareStatement(strSQL);
			ps.setInt(1, depMemphisSN);
			ps.setInt(2, wid.getLatestDepMemphisDetailId(depMemphisSN));
			ps.setString(3,squadId);
			ps.setString(4,fileName);
			ps.setInt(5, wid.getLatestDepVer(squadId, fileName) );
			ps.setString(6,"");
			ps.setString(7,isSuccess);
			ps.setString(8,result.toString());
			ps.setString(9,"t");			//是否為理論值
			ps.setString(10,isDep?"t":"f");			//辨別這次的動作是部署還是下線
			ps.execute();
			
		} catch (Exception e) {
			wid.errLog(e);
			res = e.toString();
			int depMemphisSN=0;
			if( !isMasterDataOK ) {
				String strSQL = "INSERT INTO depmemphis (svnUSR,svnURL,depMemphisId,cDT,creatorId,depType) VALUES (?,?,?,?,?,?)";
				try {
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, svnUSR);
					ps.setString(2, svnURL);
					ps.setLong(3, depId);
					ps.setTimestamp(4, wid.cDT());
					ps.setString(5, empId);
					ps.setInt(6, 2);
					ps.execute();
					depMemphisSN = wid.getDepSN(depId);
				} catch (Exception e1) {
					wid.errLog(e1);
				}
			}
			String strSQL = "INSERT INTO depmemphisdetail (depMemphisSN,depMemphisDetailId,squadId,fileName,fileVer,relativePath,isSuccess,errMsg,isAssume,isDep) VALUES (?,?,?,?,?,?,?,?,?,?)";
			try {
				ps = conn.prepareStatement(strSQL);
				ps.setInt(1, depMemphisSN);
				ps.setInt(2, wid.getLatestDepMemphisDetailId(depMemphisSN));
				ps.setString(3,squadId);
				ps.setString(4,fileName);
				ps.setInt(5, wid.getLatestDepVer(squadId, fileName) );
				ps.setString(6,"");
				ps.setString(7,"f");
				ps.setString(8,wid.errProcess(e));
				ps.setString(9, "t" );				//是否理論值
				ps.setString(10, isDep?"t":"f");	//是否為部署
				ps.execute();
			} catch (Exception e1) {
				wid.errLog(e1);
			}
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}
			} catch (SQLException e) {e.printStackTrace();}
			if ( client != null) {client.close();}
			if ( cmdCtx != null) {cmdCtx.disconnectController();}
		}
        response.getWriter().write(res);
	}

}
